# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '2019127': {  # 百合支付  微信费率3.5%(100---10000)下发的单笔是（100---49999 结算周期：D+0
        'API_KEY': 'pbiwMOHGEwpVBmcLVwkxJjQVIOEXnKtG',
        'gateway': 'https://api.lily-pay.com/Pay',
    },
    '2019118': {  # 拼多多支付宝费率3.8%  充值单笔（100---5000  100的倍数）
        'API_KEY': 'qiNHexVImyWjStXofznhPGdNRxbmTVTw',
        'gateway': 'https://api.lily-pay.com/Pay',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_pay_type(service):
    if service == 'alipay':
        return 'zfbwap'
    elif service == 'wechat':
        return 'wxwap'
    elif service == 'alipay_bank':
        return 'bank'
    else:
        return 'zfbwap'


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


# 签名【md5(商务号+商户订单号+支付金额+异步通知地址+商户秘钥)】
def generate_sign(parameter, key):
    s = parameter['fxid'] + parameter['fxddh'] + parameter['fxfee'] + parameter['fxnotifyurl'] + key
    _LOGGER.info('sign str:%s' % s)
    m = hashlib.md5()
    m.update(s.encode('utf-8'))
    return m.hexdigest()


def notify_sign(parameter, key):
    s = parameter['fxstatus'] + parameter['fxid'] + parameter['fxddh'] + parameter['fxfee'] + key
    _LOGGER.info('sign str:%s' % s)
    m = hashlib.md5()
    m.update(s.encode('utf-8'))
    return m.hexdigest()


def verify_notify_sign(params, key):
    sign = params['fxsign']
    calculated_sign = notify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("newbaihepay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    # 商户ID唯一标识
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')
    parameter_dict = OrderedDict((
        # 商务号
        ('fxid', str(app_id)),
        # 商户订单号
        ('fxddh', str(pay.id)),
        # 商品名称
        ('fxdesc', 'charge'),
        # 支付金额
        ('fxfee', str(pay_amount)),
        # 异步通知地址，异步接收支付结果通知的回调地址
        ('fxnotifyurl', '{}/pay/api/{}/newbaihepay/{}'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        # 同步通知地址，支付成功直接跳转的地址
        ('fxbackurl', '{}/pay/api/{}/newbaihepay/'.format(
            settings.NOTIFY_PREFIX, settings.RETURN_PATH)),
        # 请求类型
        ('fxpay', _get_pay_type(service)),
        # 支付用户IP地址
        ('fxip', _get_device_ip(info)),
        # 附加信息
        ('fxattch', 'nothing'),
    ))
    parameter_dict['fxsign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("newbaihepay create data: %s", json.dumps(parameter_dict))
    html_text = _build_form(parameter_dict, _get_gateway(app_id))
    cache_id = redis_cache.save_html(pay.id, html_text)
    _LOGGER.info('newbaihepay url: %s', settings.PAY_CACHE_URL + cache_id)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# OK
def check_notify_sign(request, app_id):
    _LOGGER.info("newbaihepay notify POST: %s", request.POST)
    data = dict(request.POST.iteritems())
    _LOGGER.info("newbaihepay notify data: %s", data)
    api_key = _get_api_key(app_id)
    # 校验sign
    verify_notify_sign(data, api_key)
    # 商户订单号
    pay_id = data['fxddh']
    # ip检查
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("newbaihepay fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('newbaihepay event does not contain pay ID')
    # 获取支付订单信息
    pay = order_db.get_pay(pay_id)
    if not pay:
        raise ParamError('newbaihepay pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('newbaihepay pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['fxstatus'])
    trade_no = str(data['fxddh'])
    total_fee = float(data['fxfee'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    # 交易条件的判断，信息对比等
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '1':
        _LOGGER.info('newbaihepay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


# 查询订单接口,未开通，开通后添加
def query_charge(pay, app_id):
    pass
